<?php
namespace App\Http\Responses;

use App\Exceptions\ExceptionCode;

trait RespondsJson
{

    /**
     * json response
     *
     * @param object|array|string $data  exception、
     * @param int   $status
     * @param array $headers
     * @param int   $options
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondJson($data = null, $status = 200, array $headers = [], $options = 0)
    {
        $response = [
            'code' => ExceptionCode::SUCCESS_CODE,
            'message' => ExceptionCode::SUCCESS_MESSAGE,
        ];

        if (is_string($data)) {  // simple string
            $response['message'] = $data;
        } elseif (is_array($data)) {
            $response = array_merge($response, $data);
        } elseif ($data instanceof \Exception) {
            $response = $this->morphExceptionForJsonResponse($data);
        }

        return response()->json($response, $status, $headers, $options);
    }

    /*
     * morph exception for json response
     *
     * @param Exception $ex exception
     *
     * @return array
     */
    private function morphExceptionForJsonResponse(\Exception $ex)
    {
        $code = $ex->getCode() ?: ExceptionCode::GENERAL;
        $response = ['code' => $code, 'message' => $ex->getMessage()];

        if (config('app.debug')) { // in case debug enabled
            $response['trace'] = array_slice($ex->getTrace(), 0, 10);
        }

        return $response;
    }
}
